package com.springboot.file.ftp;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Objects;

/**
 * 文件工具
 */
@Slf4j
public class FileCommonUtil {

    /**ftp*/
    public final static String FTP_TYPE = "1";

    /**fastdfs*/
    public final static String FASTDFS_TYPE = "2";

    /**oss*/
    public final static String OSS_TYPE = "3";

    public static File multipartFileToFile(MultipartFile file) throws IOException {

        File toFile = null;
        if (file!=null && file.getSize() > 0)  {
            InputStream ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        OutputStream os = null;
        try {
            os = Files.newOutputStream(file.toPath());
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }

        } catch (IOException e) {
            log.error("inputStreamToFile:", e);
        } finally {
            try {
                os.close();
                ins.close();
            } catch (IOException e) {
                log.error("inputStreamToFile close:", e);
            }
        }
    }

}
